﻿using System;
using Microsoft.Xna.Framework;

namespace BattleFury.Lib.Extensions
{
	public static class ColorExtensions
	{
		public static Color WithOpacity(this Color color, float opacity)
		{
			return new Color(color.R, color.G, color.B, opacity);
		}

		public static Color FromHex(this Color color, string hexString)
		{
			hexString = hexString.Replace("#", "");

			if (hexString.Length % 2 == 1)
				throw new Exception("The binary key cannot have an odd number of digits");

			var arr = new byte[hexString.Length >> 1];

			for (var i = 0; i < (hexString.Length >> 1); ++i)
			{
				arr[i] = (byte)((GetHexVal(hexString[i << 1]) << 4) + (GetHexVal(hexString[(i << 1) + 1])));
			}

			var a = (byte)255;
			var r = (byte)255;
			var g = (byte)255;
			var b = (byte)255;
			if (arr.Length > 3)
			{
				r = arr[0];
				g = arr[1];
				b = arr[2];
				a = arr[3];
			}
			else
			{
				r = arr[0];
				g = arr[1];
				b = arr[2];
			}

			return new Color(r, g, b, a);
		}

		private static int GetHexVal(char hex)
		{
			var val = (int)hex;
			return val - (val < 58 ? 48 : 55);
		}
	}
}